<template>
  <div class="approval-management-container">
    <div class="header">
      <h2>成果评审管理</h2>
    </div>

    <el-card>
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="待评审" name="pending">
          <el-form :inline="true" class="filter-form">
            <el-form-item label="申报人">
              <el-select v-model="filters.studentId" placeholder="所有申报人" clearable>
                <el-option v-for="student in students" :key="student.id" :label="student.realName" :value="student.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="成果类型">
              <el-select v-model="filters.type" placeholder="全部类型" clearable>
                <el-option label="学术论文" value="论文" />
                <el-option label="专利成果" value="专利" />
                <el-option label="科研项目" value="项目" />
                <el-option label="学术奖项" value="获奖" />
                <el-option label="其他成果" value="其他" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="filterApprovals">筛选</el-button>
              <el-button @click="resetFilters">重置</el-button>
            </el-form-item>
          </el-form>

          <el-table v-loading="loading" :data="filteredPendingApprovals" style="width: 100%">
            <el-table-column prop="title" label="成果标题" />
            <el-table-column prop="type" label="成果类型" width="100" />
            <el-table-column label="申报人" width="120">
              <template #default="scope">
                {{ scope.row.student?.realName || '未知' }}
              </template>
            </el-table-column>
            <el-table-column label="提交日期" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.createdAt) }}
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="220">
              <template #default="scope">
                <el-button link type="primary" @click="viewApproval(scope.row)">查看</el-button>
                <el-button link type="success" @click="approveAchievement(scope.row)">认证</el-button>
                <el-button link type="danger" @click="rejectAchievement(scope.row)">退回</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="已评审" name="processed">
          <el-form :inline="true" class="filter-form">
            <el-form-item label="申报人">
              <el-select v-model="filters.studentId" placeholder="所有申报人" clearable>
                <el-option v-for="student in students" :key="student.id" :label="student.realName" :value="student.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="成果类型">
              <el-select v-model="filters.type" placeholder="全部类型" clearable>
                <el-option label="学术论文" value="论文" />
                <el-option label="专利成果" value="专利" />
                <el-option label="科研项目" value="项目" />
                <el-option label="学术奖项" value="获奖" />
                <el-option label="其他成果" value="其他" />
              </el-select>
            </el-form-item>
            <el-form-item label="评审结果">
              <el-select v-model="filters.status" placeholder="全部状态" clearable>
                <el-option label="已认证" value="已通过" />
                <el-option label="已退回" value="已拒绝" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="filterApprovals">筛选</el-button>
              <el-button @click="resetFilters">重置</el-button>
            </el-form-item>
          </el-form>

          <el-table v-loading="loading" :data="filteredProcessedApprovals" style="width: 100%">
            <el-table-column prop="title" label="成果标题" />
            <el-table-column prop="type" label="成果类型" width="100" />
            <el-table-column label="申报人" width="120">
              <template #default="scope">
                {{ scope.row.student?.realName || '未知' }}
              </template>
            </el-table-column>
            <el-table-column label="提交日期" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.createdAt) }}
              </template>
            </el-table-column>
            <el-table-column label="评审日期" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.updatedAt) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="评审状态" width="120">
              <template #default="scope">
                <el-tag :type="scope.row.status === '已通过' ? 'success' : 'danger'">
                  {{ scope.row.status === '已通过' ? '已认证' : '已退回' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="120">
              <template #default="scope">
                <el-button link type="primary" @click="viewApproval(scope.row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 查看审批详情对话框 -->
    <el-dialog v-model="showViewDialog" title="成果评审详情" width="50%">
      <div class="approval-detail" v-if="currentApproval">
        <div class="detail-item">
          <span class="label">成果标题：</span>
          <span class="value">{{ currentApproval.title }}</span>
        </div>
        <div class="detail-item">
          <span class="label">成果类型：</span>
          <span class="value">{{ currentApproval.type }}</span>
        </div>
        <div class="detail-item">
          <span class="label">申报人：</span>
          <span class="value">{{ currentApproval.student?.realName || '未知' }}</span>
        </div>
        <div class="detail-item" v-if="currentApproval.authors">
          <span class="label">作者/参与者：</span>
          <span class="value">{{ currentApproval.authors }}</span>
        </div>
        <div class="detail-item" v-if="currentApproval.journal">
          <span class="label">期刊/会议名称：</span>
          <span class="value">{{ currentApproval.journal }}</span>
        </div>
        <div class="detail-item" v-if="currentApproval.patentNo">
          <span class="label">专利号/授权号：</span>
          <span class="value">{{ currentApproval.patentNo }}</span>
        </div>
        <div class="detail-item" v-if="currentApproval.projectNo">
          <span class="label">项目编号：</span>
          <span class="value">{{ currentApproval.projectNo }}</span>
        </div>
        <div class="detail-item" v-if="currentApproval.publishDate">
          <span class="label">发表/获批日期：</span>
          <span class="value">{{ formatDate(currentApproval.publishDate) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">提交日期：</span>
          <span class="value">{{ formatDate(currentApproval.createdAt) }}</span>
        </div>
        <div class="detail-item" v-if="currentApproval.updatedAt">
          <span class="label">评审日期：</span>
          <span class="value">{{ formatDate(currentApproval.updatedAt) }}</span>
        </div>
        <div class="detail-item" v-if="currentApproval.status !== '待审核'">
          <span class="label">评审状态：</span>
          <span class="value">
            <el-tag :type="currentApproval.status === '已通过' ? 'success' : 'danger'">
              {{ currentApproval.status === '已通过' ? '已认证' : '已退回' }}
            </el-tag>
          </span>
        </div>
        <div class="detail-item">
          <span class="label">成果概述：</span>
          <p class="value description">{{ currentApproval.description }}</p>
        </div>
        <div class="detail-item" v-if="currentApproval.comments">
          <span class="label">评审意见：</span>
          <p class="value feedback">{{ currentApproval.comments }}</p>
        </div>
        <div class="detail-item" v-if="currentApproval.attachmentUrl">
          <span class="label">证明材料：</span>
          <div class="value">
            <el-button type="primary" link @click="downloadAttachment(currentApproval.attachmentUrl)">下载材料</el-button>
          </div>
        </div>

        <div class="approval-actions" v-if="currentApproval.status === '待审核'">
          <el-divider content-position="left">评审操作</el-divider>
          <el-form :model="reviewForm" label-width="120px">
            <el-form-item label="评审结果">
              <el-radio-group v-model="reviewForm.result">
                <el-radio label="approve">认证</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-dialog>

    <!-- 快速审核对话框 -->
    <el-dialog v-model="showQuickReviewDialog" :title="quickReviewAction === 'approve' ? '通过审核' : '拒绝审核'" width="40%">
      <div class="quick-review-form" v-if="currentApproval">
        <p>您正在{{ quickReviewAction === 'approve' ? '通过' : '拒绝' }}以下成果：</p>
        <div class="approval-info">
          <p><strong>标题：</strong>{{ currentApproval.title }}</p>
          <p><strong>学生：</strong>{{ currentApproval.student?.realName || '未知' }}</p>
          <p><strong>类型：</strong>{{ currentApproval.type }}</p>
        </div>
        <el-form :model="reviewForm" label-width="120px">
          <el-form-item label="审核意见">
            <el-input 
              v-model="reviewForm.comments" 
              type="textarea" 
              rows="4" 
              :placeholder="quickReviewAction === 'approve' ? '请输入通过意见（可选）' : '请输入拒绝原因（必填）'"
              :required="quickReviewAction === 'reject'"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showQuickReviewDialog = false">取消</el-button>
          <el-button type="primary" @click="submitQuickReview" :loading="submitting">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, onMounted, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import TeacherService from '@/api/teacher'

interface Student {
  id: number
  username: string
  realName: string
}

interface Approval {
  id: number
  title: string
  type: string
  description: string
  authors?: string
  journal?: string
  patentNo?: string
  projectNo?: string
  publishDate?: string
  status: string
  attachmentUrl?: string
  createdAt: string
  updatedAt?: string
  comments?: string
  student?: {
    id: number
    username: string
    realName: string
  }
  reviewer?: {
    id: number
    username: string
    realName: string
  }
}

export default defineComponent({
  name: 'ApprovalManagement',
  setup() {
    const loading = ref(true)
    const submitting = ref(false)
    const pendingApprovals = ref<Approval[]>([])
    const processedApprovals = ref<Approval[]>([])
    const students = ref<Student[]>([])
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const activeTab = ref('pending')
    const showViewDialog = ref(false)
    const showQuickReviewDialog = ref(false)
    const currentApproval = ref<Approval | null>(null)
    const quickReviewAction = ref<'approve' | 'reject'>('approve')

    const filters = reactive({
      studentId: '',
      type: '',
      status: ''
    })

    const reviewForm = reactive({
      result: 'approve',
      comments: ''
    })

    const filteredPendingApprovals = computed(() => {
      let result = [...pendingApprovals.value]
      
      if (filters.studentId) {
        result = result.filter(a => a.student && a.student.id.toString() === filters.studentId)
      }
      
      if (filters.type) {
        result = result.filter(a => a.type === filters.type)
      }
      
      return result
    })

    const filteredProcessedApprovals = computed(() => {
      let result = [...processedApprovals.value]
      
      if (filters.studentId) {
        result = result.filter(a => a.student && a.student.id.toString() === filters.studentId)
      }
      
      if (filters.type) {
        result = result.filter(a => a.type === filters.type)
      }
      
      if (filters.status) {
        result = result.filter(a => a.status === filters.status)
      }
      
      return result
    })

    const formatDate = (dateString: string) => {
      if (!dateString) return ''
      
      // 转换ISO格式日期为更友好的格式
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN', { 
        year: 'numeric', 
        month: '2-digit', 
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    const fetchStudents = async () => {
      try {
        const response = await TeacherService.getMyStudents()
        students.value = response.data
      } catch (error: any) {
        console.error('获取学生列表失败', error)
        ElMessage.error('获取学生列表失败')
      }
    }

    const fetchApprovals = async () => {
      loading.value = true
      try {
        if (activeTab.value === 'pending') {
          const response = await TeacherService.getPendingAchievements()
          pendingApprovals.value = response.data
          total.value = response.data.length
        } else {
          const response = await TeacherService.getReviewedAchievements()
          processedApprovals.value = response.data
          total.value = response.data.length
        }
      } catch (error: any) {
        console.error('获取审核列表失败', error)
        ElMessage.error('获取审核列表失败')
      } finally {
        loading.value = false
      }
    }

    const handleTabClick = () => {
      currentPage.value = 1
      fetchApprovals()
    }

    const filterApprovals = () => {
      // 使用计算属性进行前端过滤
    }

    const resetFilters = () => {
      filters.studentId = ''
      filters.type = ''
      filters.status = ''
    }

    const handleSizeChange = (val: number) => {
      pageSize.value = val
    }

    const handleCurrentChange = (val: number) => {
      currentPage.value = val
    }

    const viewApproval = async (approval: Approval) => {
      try {
        const response = await TeacherService.getAchievementById(approval.id)
        currentApproval.value = response.data
        reviewForm.result = 'approve'
        reviewForm.comments = ''
        showViewDialog.value = true
      } catch (error: any) {
        ElMessage.error('获取成果详情失败')
      }
    }

    const approveAchievement = async (approval: Approval) => {
      try {
        const response = await TeacherService.getAchievementById(approval.id)
        currentApproval.value = response.data
        quickReviewAction.value = 'approve'
        reviewForm.comments = ''
        showQuickReviewDialog.value = true
      } catch (error: any) {
        ElMessage.error('获取成果详情失败')
      }
    }

    const rejectAchievement = async (approval: Approval) => {
      try {
        const response = await TeacherService.getAchievementById(approval.id)
        currentApproval.value = response.data
        quickReviewAction.value = 'reject'
        reviewForm.comments = ''
        showQuickReviewDialog.value = true
      } catch (error: any) {
        ElMessage.error('获取成果详情失败')
      }
    }

    const submitReview = async () => {
      if (!currentApproval.value) return
      
      const status = reviewForm.result === 'approve' ? '已通过' : '已拒绝'
      
      if (reviewForm.result === 'reject' && !reviewForm.comments.trim()) {
        ElMessage.warning('拒绝审核时必须填写审核意见')
        return
      }
      
      submitting.value = true
      try {
        await TeacherService.reviewAchievement({
          achievementId: currentApproval.value.id,
          status: status,
          comments: reviewForm.comments
        })
        
        ElMessage.success(`成果已${status}`)
        showViewDialog.value = false
        fetchApprovals()
      } catch (error: any) {
        ElMessage.error(error.response?.data?.message || '审核提交失败')
      } finally {
        submitting.value = false
      }
    }

    const submitQuickReview = async () => {
      if (!currentApproval.value) return
      
      const status = quickReviewAction.value === 'approve' ? '已通过' : '已拒绝'
      
      if (quickReviewAction.value === 'reject' && !reviewForm.comments.trim()) {
        ElMessage.warning('拒绝审核时必须填写审核意见')
        return
      }
      
      submitting.value = true
      try {
        await TeacherService.reviewAchievement({
          achievementId: currentApproval.value.id,
          status: status,
          comments: reviewForm.comments
        })
        
        ElMessage.success(`成果已${status}`)
        showQuickReviewDialog.value = false
        fetchApprovals()
      } catch (error: any) {
        ElMessage.error(error.response?.data?.message || '审核提交失败')
      } finally {
        submitting.value = false
      }
    }

    const downloadAttachment = (url: string) => {
      // 在实际项目中，这里会下载附件
      window.open(url, '_blank')
    }

    // 监听标签页变化重置分页
    watch(activeTab, () => {
      currentPage.value = 1
      fetchApprovals()
    })

    onMounted(() => {
      fetchStudents()
      fetchApprovals()
    })

    return {
      loading,
      submitting,
      pendingApprovals,
      processedApprovals,
      filteredPendingApprovals,
      filteredProcessedApprovals,
      students,
      total,
      currentPage,
      pageSize,
      activeTab,
      filters,
      reviewForm,
      showViewDialog,
      showQuickReviewDialog,
      currentApproval,
      quickReviewAction,
      formatDate,
      handleTabClick,
      filterApprovals,
      resetFilters,
      handleSizeChange,
      handleCurrentChange,
      viewApproval,
      approveAchievement,
      rejectAchievement,
      submitReview,
      submitQuickReview,
      downloadAttachment
    }
  }
})
</script>

<style scoped>
.approval-management-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}

.filter-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.approval-detail {
  padding: 10px;
}

.detail-item {
  margin-bottom: 15px;
}

.label {
  font-weight: bold;
  color: #606266;
  margin-right: 10px;
}

.description, .feedback {
  white-space: pre-line;
  line-height: 1.6;
  margin-top: 5px;
  color: #606266;
}

.feedback {
  color: #67c23a;
}

.approval-actions {
  margin-top: 30px;
}

.approval-info {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.approval-info p {
  margin: 5px 0;
}
</style> 